package com.juyu.miliao.authentication.service;

import com.juyu.miliao.authentication.cache.IconCache;
import com.juyu.miliao.authentication.cache.IconOfficialCache;
import com.juyu.miliao.authentication.cache.NickNameCache;
import com.juyu.miliao.authentication.config.IdCreater;
import com.juyu.miliao.authentication.constant.LoginTypeConstant;
import com.juyu.miliao.authentication.dao.mysql.*;
import com.juyu.miliao.authentication.dao.redis.UserRedisDao;
import com.juyu.miliao.authentication.domain.*;
import com.juyu.miliao.common.constant.EnumType;
import com.juyu.miliao.common.constant.PhoneSystemConstant;
import com.juyu.miliao.common.domain.CommonHead;
import com.juyu.miliao.common.domain.QQInfo;
import com.juyu.miliao.common.domain.Subject;
import com.juyu.miliao.common.domain.WXInfo;
import com.juyu.miliao.common.domain.dto.QqDTO;
import com.juyu.miliao.common.exception.ConsumeRuntimeException;
import com.juyu.miliao.common.exception.IllegalParamException;
import com.juyu.miliao.common.security.exception.*;
import com.juyu.miliao.common.util.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Optional;

@Service
public class UserService {
    private final static int sendBeans = 10000;
    @Resource
    private UserLoginDao userLoginDao;
    @Resource
    private UserDao userDao;
    @Resource
    private UserWalletDao userWalletDao;
    @Resource
    private UserCountDao userCountDao;
    @Resource
    private UserRedisDao userRedisDao;
    @Resource
    private IdCreater idCreater;
    @Resource
    private RegisterAddressService registerAddressService;

    @Resource
    private ConfigAppService configAppService;

    @Resource
    private PackageOnlineService packageOnlineService;

    @Resource
    private VersionService versionService;

    @Resource
    private VerificationCodeService verificationCodeService;

    @Resource
    private MakeMoneyDao makeMoneyDao;
    @Resource
    private ConfigQqService configQqService;
    @Resource
    private OpenApiService openApiService;
    @Resource
    private UserInvitationBindingInfoDao userInvitationBindingInfoDao;
    @Resource
    private AppKeyService appKeyService;
    @Resource
    private BillDetailDao billDetailDao;

    private final Logger logger = LoggerFactory.getLogger(UserService.class);

    //用户名验证码登录
    public UserDetails loadUserByVerificationCode(String username,String ip, String verificationCode, CommonHead commonHead) {
        //设备号是否被封
        if (commonHead.getDeviceNo() != null
                && !commonHead.getDeviceNo().equals("null")
                && !commonHead.getDeviceNo().equals("")
                && userRedisDao.getUserIsEnableByDeviceNo(commonHead.getDeviceNo())) {
            throw new AccountDisabledException();
        }
        //2019-10-15 ios 1.3.0以下用户不能注册登录
        if (Integer.parseInt(commonHead.getPhoneSystem()) == PhoneSystemConstant.IOS
                && commonHead.getAppPackageId().equals("xunxun-yonghu")) {
            String[] ids = commonHead.getVersionNum().split("\\.");
            if (ids.length < 3) {
                throw new IllegalParamException("版本参数错误");
            }
            if(VersionCheckUtil.compare(ids,"1.3.0")){
                throw new IllegalParamException("IOS版本异常");
            }
        }

        // TODO 产品提出 此功能 有bug
        if(!username.equals("13477992564")){
            String verification = verificationCodeService.getVerificationCodeByPhoneNum(username);
            if (verification == null || verificationCode.equals("") || !verification.equals(verificationCode))
                throw new IllegalVerificationCodeFormatException(verificationCode);
        }
        Optional<UserLogin> userByOpenId = userLoginDao.getUserByName(username);
        if(userByOpenId.isPresent()){
            //判断用户是否被封号
            if (userByOpenId.get().getEnable() == 2) {
                throw new AccountDisabledException();
            }
            User user = userDao.getUserById(userByOpenId.get().getUserId());
            //登录用户机器人推送
            loginRobotMessage(commonHead, user);
            String[] ids = commonHead.getVersionNum().split("\\.");
            if (ids.length < 3) {
                throw new IllegalParamException("版本参数错误");
            }

            //用户存在&&DeviceNoMark设备号为空 做更新操作
            updateDeviceNoValue(userByOpenId.get().getDeviceNoMark(), userByOpenId.get().getUserId(), commonHead);
            Boolean isAudit = versionService.compareVersion(commonHead.getIp(), ids
                    , Integer.parseInt(commonHead.getPhoneSystem()), commonHead.getChannel(),
                    commonHead.getAppPackageId(), commonHead.getVersionNum());
            //手机号登录
            return new Subject(userByOpenId.get().getUserId(), user.getSex(), user.getNickName(),
                    user.getIcon(), user.getIsVip(), user.getIsHost(),
                    commonHead.getChannel(), false, commonHead.getAppPackageId(),
                    isAudit, userByOpenId.get().getUsername(),1);
        }
        noNewUserRegister(commonHead.getChannel());
        UserLogin userLogin = new UserLogin(idCreater.newUserId());
        userLogin.setUsername(username);

        // 用户名不存在 做新增插入操作
        String nickname = NickNameCache.INSTANCE.getRandomNickName().getNickname();
        if(SubstrUtil.length(nickname)>16){
            nickname = nickname.substring(0, 8);
        }
        if(commonHead.getDeviceNo()!=null){
            userLogin.setDeviceNoMark(commonHead.getDeviceNo());
        }
        userLogin.setNickName(nickname);

        userLogin.setPhoneType(CommonUtil.null2Int(commonHead.getPhoneSystem()));
        userLogin.setVersionNum(commonHead.getVersionNum());
        userLogin.setLoginType(LoginTypeConstant.PHONE_NUM);
        userLogin.setAge(null);
        userLogin.setChannelId(commonHead.getChannel());
        userLogin.setAppPackageId(commonHead.getAppPackageId());
        //存入应用分组,线上线下,用于统计
        userLogin.setGroupType(configAppService.getGroupType(commonHead.getAppPackageId(), commonHead.getPhoneSystem()));
        userLogin.setOnline(packageOnlineService.getOnline(commonHead));
        if(commonHead.getDeviceNo()!= null){
            //存储设备号
            userLogin.setDeviceNoMark(commonHead.getDeviceNo());
        }

        userLoginDao.addUserLogin(userLogin);
        // 邀请赚钱 保存邀请人和被邀请人
        if(!StringUtils.isEmpty(commonHead.getActiveUserId())){
            UserInvitationBindingInfo userInvitationBindingInfo = new UserInvitationBindingInfo();
            userInvitationBindingInfo.setInvitedUserId(userLogin.getUserId());
            userInvitationBindingInfo.setInviteUserId(Long.parseLong(commonHead.getActiveUserId()));
            userInvitationBindingInfoDao.add(userInvitationBindingInfo);
        }
        //用户名放入缓存
        User user = new User();
        user.setUserId(userLogin.getUserId());
        user.setNickName(nickname);
        if(commonHead.getAppPackageId().equals("xunxun-yonghu")){
            user.setSex(1);
        }else if(commonHead.getAppPackageId().equals("xunxun-zhubo")){
            user.setSex(2);
        }
        user.setChannel(commonHead.getChannel());
        user.setIcon(IconOfficialCache.INSTANCE.getRandomIcon().getIconUrl());
        user.setGroupType(userLogin.getGroupType());
        user.setPhoneSystem(userLogin.getPhoneType());
        userDao.addUser(user);
        userWalletDao.addUserWallet(userLogin.getUserId());
        userCountDao.addUserCount(userLogin.getUserId());
       //新注册三天内用户
       userRedisDao.addThreeDaysNewUser(user.getUserId());
        //昵称缓存
//		userRedisDao.addUserIdAndNickName(userLogin.getUserId(), nickName);
        userRedisDao.addUserName(username, userLogin.getUserId());
        //注册用户机器人推送
        registerRobotMessage(commonHead, user);
        newUserMakeMoney(userLogin.getUserId(),commonHead);
        //保存Ip地址
        if (StringUtils.isNotEmpty(ip)) {
            registerAddressService.saveByIp(ip, user.getUserId());
        }
        String[] ids = commonHead.getVersionNum().split("\\.");
        if (ids.length < 3) {
            throw new IllegalParamException("版本参数错误");
        }
        VersionVO forceVersionVO =  versionService.compareVersion(ids,Integer.parseInt(commonHead.getPhoneSystem()),commonHead.getChannel(),
                commonHead.getAppPackageId(),commonHead.getVersionNum());

        //白包开启 注册用户为勿扰
        Boolean isAudit = openApiService.getForwardAudit(commonHead.getAppPackageId(),
                String.valueOf(commonHead.getPhoneSystem()),
                commonHead.getVersionNum(), commonHead.getChannel());
        logger.info("手机号审核开关判断commonHead:::::"+commonHead.toString());
        logger.info("手机号审核开关判断isAudit:::::"+isAudit);
        if(isAudit!=null && isAudit){
            logger.info("修改用户状态::::::userId::::::"+userLogin.getUserId());
            userDao.updateUserIsVideo(userLogin.getUserId());
        }
        //1.5.6新用户手机号注册赠送金币
        newUserBindingPhoneGiftDeposit(userLogin.getUserId());
        return new Subject(user.getUserId(),user.getSex(),user.getNickName(), user.getIcon(),
                user.getIsVip(),user.getIsHost(),
                commonHead.getChannel(), true, commonHead.getAppPackageId(),
                forceVersionVO.getIsAudit(),null,2);
    }

    //用户名密码登录
    public UserDetails loadUserByUsername(String username, String password, CommonHead commonHead) throws UsernameNotFoundException {
        //设备号是否被封
        if(commonHead.getDeviceNo() != null
                && !commonHead.getDeviceNo().equals("null")
                && !commonHead.getDeviceNo().equals("")
                && userRedisDao.getUserIsEnableByDeviceNo(commonHead.getDeviceNo())){
            throw new AccountDisabledException();
        }

        //2019-10-15 ios 1.3.0以下用户不能注册登录
        if (Integer.parseInt(commonHead.getPhoneSystem()) == PhoneSystemConstant.IOS
                && commonHead.getAppPackageId().equals("xunxun-yonghu")) {
            String[] ids = commonHead.getVersionNum().split("\\.");
            if (ids.length < 3) {
                throw new IllegalParamException("版本参数错误");
            }
            if(VersionCheckUtil.compare(ids,"1.3.0")){
                throw new IllegalParamException("IOS版本异常");
            }
        }

        UserLogin userLogin = userLoginDao.getUserByName(username)
                .orElseThrow(() -> new UsernameNotFoundException(username));

        //用户存在&&DeviceNoMark设备号为空 做更新操作
        updateDeviceNoValue(userLogin.getDeviceNoMark(),userLogin.getUserId(),commonHead);

        if (!password.equals(userLogin.getPassword()))
            throw new BadCredentialsException("登录密码错误：" + password);


        //判断用户是否被封 或 设备号是否被封
        if (userLogin.getEnable() == 2) {
            throw new AccountDisabledException();
        }

        User user = userDao.getUserById(userLogin.getUserId());
        //登录用户机器人推送
        loginRobotMessage(commonHead, user);
        String[] ids = commonHead.getVersionNum().split("\\.");
        if (ids.length < 3) {
            throw new IllegalParamException("版本参数错误");
        }
        Boolean isAudit =  versionService.compareVersion(commonHead.getIp(),ids
                ,Integer.parseInt(commonHead.getPhoneSystem()),commonHead.getChannel(),
                commonHead.getAppPackageId(),commonHead.getVersionNum());

        return new Subject(userLogin.getUserId(),user.getSex(), user.getNickName(),
                user.getIcon(),user.getIsVip(),user.getIsHost(),
                commonHead.getChannel(), false, commonHead.getAppPackageId(),
               isAudit,userLogin.getUsername(),1);
    }

    //手机号注册
    public UserDetails registerAndLogin(UserDetails userDetails, String nickName, int sex, String icon,
                                        String ip, CommonHead commonHead) {
        //设备号是否被封
        if(commonHead.getDeviceNo() != null
                && !commonHead.getDeviceNo().equals("null")
                && !commonHead.getDeviceNo().equals("")
                && userRedisDao.getUserIsEnableByDeviceNo(commonHead.getDeviceNo())){
            throw new AccountDisabledException();
        }
        //2019-10-15 ios 1.3.0以下用户不能注册登录
        if (Integer.parseInt(commonHead.getPhoneSystem()) == PhoneSystemConstant.IOS
                && commonHead.getAppPackageId().equals("xunxun-yonghu")) {
            String[] ids = commonHead.getVersionNum().split("\\.");
            if (ids.length < 3) {
                throw new IllegalParamException("版本参数错误");
            }
            if(VersionCheckUtil.compare(ids,"1.3.0")){
                throw new IllegalParamException("IOS版本异常");
            }
        }

        noNewUserRegister(commonHead.getChannel());
        // 用户名已存在
        Optional<Integer> userIdByUserName = userRedisDao.getUserIdByUserName(userDetails.getUsername());
        if (userIdByUserName.isPresent()) {
            throw new WrongUserNameException();
        }
        UserLogin userLogin = new UserLogin(idCreater.newUserId());
        userLogin.setUsername(userDetails.getUsername());
        userLogin.setPassword(userDetails.getPassword());
        // nickname已存在
//		Optional<Integer> userIdByNickName = userRedisDao.getUserIdByNickName(nickName);
//		if (userIdByNickName.isPresent()) {
//			throw new WrongNickNameException();
//		}
        // 用户名不存在 做新增插入操作
        userLogin.setNickName(nickName);

        userLogin.setPhoneType(CommonUtil.null2Int(commonHead.getPhoneSystem()));
        userLogin.setVersionNum(commonHead.getVersionNum());
        userLogin.setLoginType(LoginTypeConstant.PHONE_NUM);
        userLogin.setAge(null);
        userLogin.setChannelId(commonHead.getChannel());
        userLogin.setAppPackageId(commonHead.getAppPackageId());
        //存入应用分组,线上线下,用于统计
        userLogin.setGroupType(configAppService.getGroupType(commonHead.getAppPackageId(), commonHead.getPhoneSystem()));
        userLogin.setOnline(packageOnlineService.getOnline(commonHead));
       if(commonHead.getDeviceNo()!= null){
           //存储设备号
           userLogin.setDeviceNoMark(commonHead.getDeviceNo());
       }

        userLoginDao.addUserLogin(userLogin);

        //用户名放入缓存
        User user = new User();
        user.setUserId(userLogin.getUserId());
        user.setNickName(nickName);
        user.setSex(sex);
        user.setChannel(commonHead.getChannel());
        user.setIcon(icon);
        user.setGroupType(userLogin.getGroupType());
        user.setPhoneSystem(userLogin.getPhoneType());
        userDao.addUser(user);
        userWalletDao.addUserWallet(userLogin.getUserId());
        userCountDao.addUserCount(userLogin.getUserId());
        //昵称缓存
//		userRedisDao.addUserIdAndNickName(userLogin.getUserId(), nickName);
        userRedisDao.addUserName(userDetails.getUsername(), userLogin.getUserId());
        //注册用户机器人推送
        registerRobotMessage(commonHead, user);
        newUserMakeMoney(userLogin.getUserId(),commonHead);
        //保存Ip地址
        if (StringUtils.isNotEmpty(ip)) {
            registerAddressService.saveByIp(ip, user.getUserId());
        }
        String[] ids = commonHead.getVersionNum().split("\\.");
        if (ids.length < 3) {
            throw new IllegalParamException("版本参数错误");
        }
        VersionVO forceVersionVO =  versionService.compareVersion(ids,Integer.parseInt(commonHead.getPhoneSystem()),commonHead.getChannel(),
                commonHead.getAppPackageId(),commonHead.getVersionNum());

        //白包开启 注册用户为勿扰
        Boolean isAudit = openApiService.getForwardAudit(commonHead.getAppPackageId(),
                String.valueOf(commonHead.getPhoneSystem()),
                commonHead.getVersionNum(), commonHead.getChannel());
        logger.info("手机号审核开关判断commonHead:::::"+commonHead.toString());
        logger.info("手机号审核开关判断isAudit:::::"+isAudit);
        if(isAudit!=null && isAudit){
            logger.info("修改用户状态::::::userId::::::"+userLogin.getUserId());
            userDao.updateUserIsVideo(userLogin.getUserId());
        }
        //1.5.6新用户手机号注册赠送金币
        newUserBindingPhoneGiftDeposit(userLogin.getUserId());
        return new Subject(user.getUserId(),user.getSex(),user.getNickName(), user.getIcon(),
                user.getIsVip(),user.getIsHost(),
                commonHead.getChannel(), true, commonHead.getAppPackageId(),
                forceVersionVO.getIsAudit(),null,2);

    }

    //第三方 qq登录
    public UserDetails qqLogin(UserDetails userDetails, String access_token, String ip, CommonHead commonHead) {
        //设备号是否被封
        if(commonHead.getDeviceNo() != null
                && !commonHead.getDeviceNo().equals("null")
                && !commonHead.getDeviceNo().equals("")
                && userRedisDao.getUserIsEnableByDeviceNo(commonHead.getDeviceNo())){
            throw new AccountDisabledException();
        }
        //2019-10-15 ios 1.3.0以下用户不能注册登录
        if (Integer.parseInt(commonHead.getPhoneSystem()) == PhoneSystemConstant.IOS
                && commonHead.getAppPackageId().equals("xunxun-yonghu")) {
            String[] ids = commonHead.getVersionNum().split("\\.");
            if (ids.length < 3) {
                throw new IllegalParamException("版本参数错误");
            }
            if(VersionCheckUtil.compare(ids,"1.3.0")){
                throw new IllegalParamException("IOS版本异常");
            }
        }
        //获取qq配置
      //  QqDTO qqDTO = ConfigQqCache.INSTANCE.getConfig(commonHead.getAppPackageId(), Integer.valueOf(commonHead.getPhoneSystem()));
        QqDTO qqDTO = configQqService.getConfig(commonHead.getAppPackageId(), Integer.valueOf(commonHead.getPhoneSystem()));
        logger.info("获取qq配置:[{}]",qqDTO);
        QQInfo qqInfo = QQGetUserInfoUtil.doGet(access_token, userDetails.getUsername(), qqDTO.getAppid());
        if (Integer.parseInt(qqInfo.getRet()) < 0) {
            throw new ThirdPartyLoginException("QQ登录调用错误！ret：" + qqInfo.getRet() + ",msg：" + qqInfo.getMsg());
        }
        //Optional<Subject> subject = userLoginDao.getUserByOpenId(userDetails.getUsername()).map(u -> new Subject(u.getUserId()));
        Optional<UserLogin> userByOpenId = userLoginDao.getUserByOpenId(userDetails.getUsername());

        if (userByOpenId.isPresent()) {
            //判断用户是否被封号
            if (userByOpenId.get().getEnable() == 2) {
                throw new AccountDisabledException();
            }
            //用户存在&&DeviceNoMark设备号为空 做更新操作
            updateDeviceNoValue(userByOpenId.get().getDeviceNoMark(),userByOpenId.get().getUserId(),commonHead);
            User user = userDao.getUserById(userByOpenId.get().getUserId());
            //登录用户机器人推送
            loginRobotMessage(commonHead, user);
            String[] ids = commonHead.getVersionNum().split("\\.");
            if (ids.length < 3) {
                throw new IllegalParamException("版本参数错误");
            }
            VersionVO forceVersionVO =  versionService.compareVersion(ids,Integer.parseInt(commonHead.getPhoneSystem()),commonHead.getChannel(),
                    commonHead.getAppPackageId(),commonHead.getVersionNum());
            return new Subject(user.getUserId(),user.getSex(),user.getNickName(), user.getIcon(),
                    user.getIsVip(),user.getIsHost(),
                    commonHead.getChannel(), false, commonHead.getAppPackageId(),
                    forceVersionVO.getIsAudit(),userByOpenId.get().getUsername(),1);
        }
        noNewUserRegister(commonHead.getChannel());
        UserLogin userLogin = new UserLogin(idCreater.newUserId());
        userLogin.setOpenid(userDetails.getUsername());
        String nickname = qqInfo.getNickname();
        if(SubstrUtil.length(nickname)>16){
            nickname = nickname.substring(0, 8);
        }
        userLogin.setNickName(nickname);
        userLogin.setPhoneType(CommonUtil.null2Int(commonHead.getPhoneSystem()));
        userLogin.setVersionNum(commonHead.getVersionNum());
        userLogin.setLoginType(LoginTypeConstant.QQ);
        userLogin.setAge(null);
        userLogin.setChannelId(commonHead.getChannel());
        userLogin.setAppPackageId(commonHead.getAppPackageId());
        //存入应用分组,线上线下,用于统计
        userLogin.setGroupType(configAppService.getGroupType(commonHead.getAppPackageId(), commonHead.getPhoneSystem()));
        userLogin.setOnline(packageOnlineService.getOnline(commonHead));
        if(commonHead.getDeviceNo()!= null){
            //存储设备号
            userLogin.setDeviceNoMark(commonHead.getDeviceNo());
        }
        userLoginDao.addUserLogin(userLogin);
        User user = new User();
        user.setUserId(userLogin.getUserId());
//		Optional<Integer> OpNickName = userRedisDao.getUserIdByNickName(qqInfo.getNickname());
//		if (OpNickName.isPresent()) {
//			Random rand = new Random();
//			// 生成0-2的随机数
//			int randNum = rand.nextInt(9999 - 1000 + 1) + 1000;
//			nickname = qqInfo.getNickname() + randNum;
//		}
        user.setNickName(userLogin.getNickName());
        if (qqInfo.getGender().equals("男"))
            user.setSex(1);
        else
            user.setSex(2);
        user.setCity(qqInfo.getProvince() + "-" + qqInfo.getCity());
        user.setIcon(qqInfo.getFigureurl_qq_2());
        user.setChannel(commonHead.getChannel());
        user.setGroupType(userLogin.getGroupType());
        user.setPhoneSystem(userLogin.getPhoneType());
        userDao.addUser(user);
        userWalletDao.addUserWallet(userLogin.getUserId());
        userCountDao.addUserCount(userLogin.getUserId());
//		userRedisDao.addUserIdAndNickName(userLogin.getUserId(), nickname);
        userRedisDao.addUserIdAndOpenId(userLogin.getUserId(), userDetails.getUsername());
        //注册用户机器人推送
        registerRobotMessage(commonHead, user);
        newUserMakeMoney(userLogin.getUserId(),commonHead);
        //保存Ip地址
        if (StringUtils.isNotEmpty(ip)) {
            registerAddressService.saveByIp(ip, user.getUserId());
        }
        String[] ids = commonHead.getVersionNum().split("\\.");
        if (ids.length < 3) {
            throw new IllegalParamException("版本参数错误");
        }
        VersionVO forceVersionVO =  versionService.compareVersion(ids,Integer.parseInt(commonHead.getPhoneSystem()),commonHead.getChannel(),
                commonHead.getAppPackageId(),commonHead.getVersionNum());
        //1.5.6 新注册未绑定手机号用户
        userRedisDao.addNewUserBindingPhoneGiftDeposit(user.getUserId());
        return new Subject(user.getUserId(),user.getSex(),user.getNickName(), user.getIcon(),
                user.getIsVip(),user.getIsHost(),
                commonHead.getChannel(), true, commonHead.getAppPackageId(),
                forceVersionVO.getIsAudit(),null,3);

    }

    // 第三方 微信登录
    public UserDetails wxLogin(UserDetails userDetails, String access_token, String ip, CommonHead commonHead) {
        //设备号是否被封
        if(commonHead.getDeviceNo() != null
                && !commonHead.getDeviceNo().equals("null")
                && !commonHead.getDeviceNo().equals("")
                && userRedisDao.getUserIsEnableByDeviceNo(commonHead.getDeviceNo())){
            throw new AccountDisabledException();
        }
        //2019-10-15 ios 1.3.0以下用户不能注册登录
        if (Integer.parseInt(commonHead.getPhoneSystem()) == PhoneSystemConstant.IOS
            && commonHead.getAppPackageId().equals("xunxun-yonghu")) {
            String[] ids = commonHead.getVersionNum().split("\\.");
            if (ids.length < 3) {
                throw new IllegalParamException("版本参数错误");
            }
            if(VersionCheckUtil.compare(ids,"1.3.0")){
                throw new IllegalParamException("IOS版本异常");
            }
        }
        WXInfo wxInfo = WXgetUserInfoUtil.doGet(access_token, userDetails.getUsername());
        if (wxInfo.getErrcode() != null) {
            throw new ThirdPartyLoginException(
                    "微信登录调用错误！ret：" + wxInfo.getErrcode() + ",msg：" + wxInfo.getErrmsg());
        }
        Optional<UserLogin> userByOpenId = userLoginDao.getUserByOpenId(userDetails.getUsername());

        if (userByOpenId.isPresent()) {
            //判断用户是否被封号
            if (userByOpenId.get().getEnable() == 2) {
                throw new AccountDisabledException();
            }
            //用户存在&&DeviceNoMark设备号为空 做更新操作
            updateDeviceNoValue(userByOpenId.get().getDeviceNoMark(),userByOpenId.get().getUserId(),commonHead);
            User user = userDao.getUserById(userByOpenId.get().getUserId());
            //登录用户机器人推送
            loginRobotMessage(commonHead, user);
            String[] ids = commonHead.getVersionNum().split("\\.");
            if (ids.length < 3) {
                throw new IllegalParamException("版本参数错误");
            }
            VersionVO forceVersionVO =  versionService.compareVersion(ids,Integer.parseInt(commonHead.getPhoneSystem()),commonHead.getChannel(),
                    commonHead.getAppPackageId(),commonHead.getVersionNum());
            return new Subject(user.getUserId(),user.getSex(), user.getNickName(), user.getIcon(),
                    user.getIsVip(), user.getIsHost(),
                    commonHead.getChannel(), false, commonHead.getAppPackageId(),
                    forceVersionVO.getIsAudit(),userByOpenId.get().getUsername(),1);
        }
        noNewUserRegister(commonHead.getChannel());
        UserLogin userLogin = new UserLogin(idCreater.newUserId());
        userLogin.setOpenid(userDetails.getUsername());
        String nickname = wxInfo.getNickname();
        if(SubstrUtil.length(nickname)>16){
              nickname = nickname.substring(0, 8);
         }
        userLogin.setNickName(nickname);
        userLogin.setPhoneType(CommonUtil.null2Int(commonHead.getPhoneSystem()));
        userLogin.setVersionNum(commonHead.getVersionNum());
        userLogin.setLoginType(LoginTypeConstant.WEIXIN);
        userLogin.setAge(null);
        userLogin.setChannelId(commonHead.getChannel());
        userLogin.setAppPackageId(commonHead.getAppPackageId());
        //存入应用分组,线上线下,用于统计
        userLogin.setGroupType(configAppService.getGroupType(commonHead.getAppPackageId(), commonHead.getPhoneSystem()));
        userLogin.setOnline(packageOnlineService.getOnline(commonHead));
        if(commonHead.getDeviceNo()!= null){
            //存储设备号
            userLogin.setDeviceNoMark(commonHead.getDeviceNo());
        }
        userLoginDao.addUserLogin(userLogin);
        User user = new User();
        user.setUserId(userLogin.getUserId());

//		Optional<Integer> OpNickName = userRedisDao.getUserIdByNickName(wxInfo.getNickname());
//		if (OpNickName.isPresent()) {
//			Random rand = new Random();
//			// 生成0-2的随机数
//			int randNum = rand.nextInt(9999 - 1000 + 1) + 1000;
//			nickname = wxInfo.getNickname() + randNum;
//		}
        user.setNickName(userLogin.getNickName());
        if(wxInfo.getSex()!=null && !wxInfo.getSex().equals("") && !wxInfo.getSex().equals("null")
                && !wxInfo.getSex().equals("0")){
            user.setSex(Integer.parseInt(wxInfo.getSex()));
        }else{
            user.setSex(1);
        }
        user.setCity(wxInfo.getProvince() + "-" + wxInfo.getCity());
        user.setIcon(wxInfo.getHeadimgurl());
        user.setChannel(commonHead.getChannel());
        user.setGroupType(userLogin.getGroupType());
        user.setPhoneSystem(userLogin.getPhoneType());
        userDao.addUser(user);
        userWalletDao.addUserWallet(userLogin.getUserId());
        userCountDao.addUserCount(userLogin.getUserId());
        //缓存 username  nickname
//		userRedisDao.addUserIdAndNickName(userLogin.getUserId(), nickname);
        userRedisDao.addUserIdAndOpenId(userLogin.getUserId(), userDetails.getUsername());
        //注册用户机器人推送
        registerRobotMessage(commonHead, user);
        newUserMakeMoney(userLogin.getUserId(),commonHead);
        //保存Ip地址
        if (StringUtils.isNotEmpty(ip)) {
            registerAddressService.saveByIp(ip, user.getUserId());
        }
        String[] ids = commonHead.getVersionNum().split("\\.");
        if (ids.length < 3) {
            throw new IllegalParamException("版本参数错误");
        }
        VersionVO forceVersionVO =  versionService.compareVersion(ids,Integer.parseInt(commonHead.getPhoneSystem()),commonHead.getChannel(),
                commonHead.getAppPackageId(),commonHead.getVersionNum());
        //1.5.6 新注册未绑定手机号用户
        userRedisDao.addNewUserBindingPhoneGiftDeposit(user.getUserId());
        return new Subject(user.getUserId(),user.getSex(),user.getNickName(), user.getIcon(),
                user.getIsVip(),user.getIsHost(),
                commonHead.getChannel(), true, commonHead.getAppPackageId(),
                forceVersionVO.getIsAudit(),null,3);
    }

    //游客登录
    public UserDetails automaticLogon(String deviceNo, String ip, CommonHead commonHead) {
        Optional<UserLogin> userByOpenId = userLoginDao.getUserByDeviceNo(deviceNo);
        //设备号是否被封
        if(commonHead.getDeviceNo() != null
                && !commonHead.getDeviceNo().equals("null")
                && !commonHead.getDeviceNo().equals("")
                && userRedisDao.getUserIsEnableByDeviceNo(commonHead.getDeviceNo())){
            throw new AccountDisabledException();
        }

        //用户存在
        if (userByOpenId.isPresent()) {
            if (userByOpenId.get().getEnable() == 2) {
                throw new AccountDisabledException();
            }
            //用户存在&&DeviceNoMark设备号为空 做更新操作
            updateDeviceNoValue(userByOpenId.get().getDeviceNoMark(),userByOpenId.get().getUserId(),commonHead);
            User user = userDao.getUserById(userByOpenId.get().getUserId());
            //登录用户机器人推送
            loginRobotMessage(commonHead, user);
            String[] ids = commonHead.getVersionNum().split("\\.");
            if (ids.length < 3) {
                throw new IllegalParamException("版本参数错误");
            }
            VersionVO forceVersionVO =  versionService.compareVersion(ids,Integer.parseInt(commonHead.getPhoneSystem()),commonHead.getChannel(),
                    commonHead.getAppPackageId(),commonHead.getVersionNum());
            return new Subject(user.getUserId(),user.getSex(),user.getNickName(), user.getIcon(),
                    user.getIsVip(),user.getIsHost(),
                    commonHead.getChannel(), false, commonHead.getAppPackageId(),
                    forceVersionVO.getIsAudit(),userByOpenId.get().getUsername(),1);
        }
        noNewUserRegister(commonHead.getChannel());
        //用户不存在，保存用户登录信息
        UserLogin userLogin = new UserLogin(idCreater.newUserId());
        userLogin.setDeviceNo(deviceNo);
        String nickname = NickNameCache.INSTANCE.getRandomNickName().getNickname();
        if(SubstrUtil.length(nickname)>16){
            nickname = nickname.substring(0, 8);
        }
        if(commonHead.getDeviceNo()!=null){
            userLogin.setDeviceNoMark(commonHead.getDeviceNo());
        }
        userLogin.setNickName(nickname);
        userLogin.setPhoneType(CommonUtil.null2Int(commonHead.getPhoneSystem()));
        userLogin.setVersionNum(commonHead.getVersionNum());
        userLogin.setLoginType(LoginTypeConstant.TOURIST);
        userLogin.setAge(null);
        userLogin.setChannelId(commonHead.getChannel());
        userLogin.setAppPackageId(commonHead.getAppPackageId());
        //存入应用分组,线上线下,用于统计
        userLogin.setGroupType(configAppService.getGroupType(commonHead.getAppPackageId(), commonHead.getPhoneSystem()));
        userLogin.setOnline(packageOnlineService.getOnline(commonHead));

        userLoginDao.addUserLogin(userLogin);
        //保存用户基本信息
        User user = new User();
        user.setUserId(userLogin.getUserId());
        user.setNickName(userLogin.getNickName());
        user.setIcon(IconCache.INSTANCE.getRandomIcon().getIconUrl());
        user.setSex(1);
        user.setChannel(commonHead.getChannel());
        user.setGroupType(userLogin.getGroupType());
        user.setPhoneSystem(userLogin.getPhoneType());
        userDao.addUser(user);
        userWalletDao.addUserWallet(userLogin.getUserId());
        userCountDao.addUserCount(userLogin.getUserId());
        //注册用户机器人推送
        registerRobotMessage(commonHead, user);
        //保存Ip地址
        if (StringUtils.isNotEmpty(ip)) {
            registerAddressService.saveByIp(ip, user.getUserId());
        }
        String[] ids = commonHead.getVersionNum().split("\\.");
        if (ids.length < 3) {
            throw new IllegalParamException("版本参数错误");
        }
        VersionVO forceVersionVO =  versionService.compareVersion(ids,Integer.parseInt(commonHead.getPhoneSystem()),commonHead.getChannel(),
                commonHead.getAppPackageId(),commonHead.getVersionNum());
        //1.5.6 新注册未绑定手机号用户
        userRedisDao.addNewUserBindingPhoneGiftDeposit(user.getUserId());
        return new Subject(user.getUserId(),user.getSex(),user.getNickName(), user.getIcon(),
                user.getIsVip(),user.getIsHost(),
                commonHead.getChannel(), true, commonHead.getAppPackageId(),
                forceVersionVO.getIsAudit(),null,3);
    }

    /**
     * 登录用户机器人推送
     * 11-13 需求：线上版本也使用线下版本机器人逻辑
     */
    private void loginRobotMessage(CommonHead commonHead, User user) {
        //线上机器人消息队列-登录用户
//        if(commonHead.getAppPackageId().equals("") || commonHead.getAppPackageId().equals("huami")){
//            if (user.getIsHost() == 2 && !commonHead.getChannel().equals("hm_oppo")
//                    && !commonHead.getChannel().equals("hm_huawei"))
//                userRedisDao.userLoginMessage(user.getUserId());
//        }
    }

    /**
     * 注册用户机器人推送
     * 11-13 需求：线上版本也使用线下版本机器人逻辑
     */
    private void registerRobotMessage(CommonHead commonHead, User user) {
//        OpenApiDTO dto = openApiService.getOpenApiDTO(commonHead);
//        //机器人消息不为null且机器人消息关闭时才关闭
//        if (dto != null && dto.getApiResourceDTO() != null && !dto.getApiResourceDTO().getRobotMsg()) {
//            logger.info("不发送机器人消息info---{}",dto.toString());
//            return;
//        }
//
//        //根据包区分发送
//        logger.info("发送机器人消息commonHead---{}",commonHead.toString());
//        Integer packageGroup = configAppService.getPackageGroup(commonHead.getAppPackageId(), commonHead.getPhoneSystem());
//        logger.info("发送机器人消息packageGroup---{}",packageGroup);
//        if (packageGroup != null && packageGroup == PackageGroupConstant.VEST) {
//            userRedisDao.vestRegisterMessage(user.getUserId(), EnumType.VEST.state);
//            logger.info("发送机器人消息isOnline-----{}",EnumType.VEST.state);
//        } else {
//            userRedisDao.vestRegisterMessage(user.getUserId(), EnumType.ONLINE.state);
//            logger.info("发送机器人消息isOnline-----{}",EnumType.ONLINE.state);
//        }
    }

    /**
     * 2019-04-24禁止miban_huawei用户注册
     * @param channel
     */
    private void noNewUserRegister(String channel){
        if(channel.equals("miban_huawei")){
            throw new ConsumeRuntimeException("新用户注册已关闭");
        }
    }

    /**
     * 2019-05-08 新用户注册 邀请赚钱判断
     * @param userId 新用户userId
     * @param commonHead 邀请赚钱参数
     */
    private void newUserMakeMoney(long userId,CommonHead commonHead){
        String activeUserId = commonHead.getActiveUserId();
        String verifyOpenId = commonHead.getVerifyOpenId();
        String deviceNo = commonHead.getDeviceNo();
        if(activeUserId==null || verifyOpenId==null || deviceNo==null
                ||  verifyOpenId.equals("") || verifyOpenId.equals("null")
                || activeUserId.equals("") || activeUserId.equals("null")
                || deviceNo.equals("") || deviceNo.equals("null")){
            return;
        }

        int countVerifyOpenId = makeMoneyDao.getCountVerifyOpenId(verifyOpenId);
        if(countVerifyOpenId > 0){
            return;
        }
        int countVerifyDeviceNo = makeMoneyDao.getCountVerifyDeviceNo(deviceNo);
        if(countVerifyDeviceNo > 0){
            return;
        }

        int temp = makeMoneyDao.insertMakeMoney(activeUserId, userId, EnumType.MAKE_MONEY_LOGON.state,
                verifyOpenId,deviceNo);
        if(temp > 0){
            userWalletDao.reviseDeposit(Long.parseLong(activeUserId),EnumType.MAKE_MONEY_LOGON.state);
        }
    }

    /**
     * 更改用户设备号
     * @param deviceNoMark
     * @param userId
     * @param commonHead
     */
    public void updateDeviceNoValue(String deviceNoMark,long userId,CommonHead commonHead){
        if (!commonHead.getDeviceNo().equals("")) {
            if (deviceNoMark == null || deviceNoMark.equals("")) {
                userLoginDao.updateUserLoginForDeviceNo(commonHead.getDeviceNo(), userId);
            }
        }
    }

    //1.5.6新用户手机号注册赠送金币
    private void newUserBindingPhoneGiftDeposit(long userId){
        Appkey appkey = appKeyService.getAppKeyByKey("newUserBindingPhoneGiftDeposit");
        if(appkey==null)
            throw new AccountDisabledException("newUserBindingPhoneGiftDeposit配置参数错误");
        userWalletDao.reviseDeposit(userId,Integer.parseInt(appkey.getValue()));
        logger.info("新用户注册userId::::::"+userId+",appkey.getValue()::::::"+appkey.getValue());
        BillDetailDeposit billDetailDeposit = new BillDetailDeposit();
        billDetailDeposit.setRecordType(15);
        billDetailDeposit.setInUserId(userId);
        billDetailDeposit.setOutUserId(0);
        billDetailDeposit.setSpend(Integer.parseInt(appkey.getValue()));
        billDetailDeposit.setDiamond(0);
        billDetailDeposit.setRatio(0);
        billDetailDao.insertBillDetailDeposit(billDetailDeposit);
    }

}
